package com.qinghe.pro.util.log;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.qinghe.pro.util.log.impl.LogUitls;
import com.qinghe.utils.Exceptions;

public class LogInterceptor extends HandlerInterceptorAdapter {
	private final static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

	private LogAPI logAPI;

	/**   
	 * 将request存入LogUitl中的LOCAL_REQUEST。
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception  
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)  
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		LogUitls.putRequest(request);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return;
		}
		
		final HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		
		final Log log = method.getAnnotation(Log.class);
		if (log != null) {
			final LogMessageObject logMessageObject = LogUitls.getArgs();
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						LogMessageObject defaultLogMessageObject = logMessageObject;
						if (defaultLogMessageObject == null) {
							defaultLogMessageObject = LogMessageObject.newIgnore();
						}
						
						// 判断是否写入log
						if (defaultLogMessageObject.isWritten()) {
							logAPI.log(log.type(), log.message(), defaultLogMessageObject.getObjects());
						}
					} catch (Exception e) {
						logger.error(Exceptions.getStackTraceAsString(e));
					}
				}
			}).start();
		}
	}

	/**
	 * 清除LogUitl中的LOCAL_REQUEST。
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception  
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)  
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		LogUitls.removeRequest();
	}

	public void setLogAPI(LogAPI logAPI) {
		this.logAPI = logAPI;
	}

}
